package com.lap.scp.admin.support;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.lap.scp.admin.bean.TreeDO;
import com.lap.scp.admin.domain.ResourcesDO;

/**
 * 添加资源支持类
 * 
 * @author 郭凯
 * @version 2017年9月3日14:08:29
 */
@Service("resourcesSupport")
public class ResourcesSupport {

	/**
	 * 过滤功能节点、本节点
	 * 
	 * @param list
	 *            需要转换的资源数据
	 * @return 集合
	 */
	public List<TreeDO> getTree(List<ResourcesDO> list) {
		List<TreeDO> treeList = new ArrayList<>();

		TreeDO treeDO = null;
		for (ResourcesDO res : list) {
			if (res.getPid() == 0) {
				treeDO = new TreeDO(res.getId(), res.getName());

				List<TreeDO> childrenList = this.children(res, list);
				if (childrenList.isEmpty()) {
					treeDO.setChildren(null);
				} else {
					treeDO.setChildren(childrenList);
				}
				treeList.add(treeDO);
			}
		}
		return treeList;
	}

	/**
	 * 根据上一级资源，找出下一级的资源数据
	 * 
	 * @param parent
	 *            上一级节点数据
	 * @param list
	 *            需要转换的资源数据
	 * @return 集合
	 */
	public List<TreeDO> children(ResourcesDO parent, List<ResourcesDO> list) {
		List<TreeDO> treeList = new ArrayList<>();

		TreeDO treeDO = null;
		for (ResourcesDO res : list) {
			if (res.getPid() == parent.getId()) {
				treeDO = new TreeDO(res.getId(), res.getName());
				List<TreeDO> childrenList = this.children(res, list);

				if (childrenList.isEmpty()) {
					treeDO.setChildren(null);
				} else {
					treeDO.setChildren(childrenList);
				}
				treeList.add(treeDO);
			}
		}
		return treeList;
	}

	/**
	 * 将绑定资源的变成树形数据
	 * 
	 * @param resList
	 *            资源数据
	 * @param checked
	 *            已选中的资源
	 * @return 集合
	 */
	public List<TreeDO> getTree(List<ResourcesDO> resList, List<Integer> checked) {
		List<TreeDO> treeList = new ArrayList<>();

		TreeDO treeDO = null;
		for (ResourcesDO res : resList) {
			treeDO = new TreeDO(res.getId(), res.getName());
			treeDO.setPid(res.getPid());

			if (checked != null && checked.contains(res.getId())) {
				treeDO.setChecked(true);
			}
			treeList.add(treeDO);
		}
		return treeList;
	}
}
